﻿@inherits BootstrapInputBase<string>

<div class="dropdown w-100">

    <input id="@Id-input"
           class="@ClassName"
           data-bs-toggle="dropdown"
           aria-haspopup="true"
           aria-expanded="false"
           autocomplete="off"
           readonly="@ReadOnly"
           value="@InputFilter"
           @attributes="Attributes"
           @ref="RefThis"
           @oninput="OnInputAsync"
           @onblur="OnBlurAsync"
           @onkeydown="OnKeydownAsync"
           disabled="@IsDisabled" />

    @if (!string.IsNullOrWhiteSpace(ErrorMessage))
    {
        <div class="invalid-feedback mt-0 mb-1">@ErrorMessage</div>
    }

    <div class="dropdown-menu" aria-labelledby="@Id-input">

        @if (Items is not null && Items.Any())
        {
            @foreach (var item in Items)
            {
                <a class="dropdown-item h6" href="javascript:;" @onclick=@(_ => SelectItemAsync(item))>
                    @item.Text
                    <small class="mb-0">
                        @item.Value
                    </small>
                </a>
            }
        }
        else
        {
            <a class="dropdown-item disabled">@(Items is null ? "请输入.." : "（未找到）")</a>
        }

    </div>

</div>

@code
{
    // public string Id => $"{Guid.NewGuid()}";
    List<SelectedItem>? Items;
    ElementReference RefThis;

    SelectedItem? SelectedItem;
    string? InputFilter;
    Dictionary<string, object> Attributes { get; set; } = new Dictionary<string, object>();

    // string CssClass => (!ReadOnly && !string.IsNullOrWhiteSpace(ErrorMessage)) ?
    //     "form-control dropdown-toggle is-invalid" : "form-control dropdown-toggle";


    [Parameter]
    public string? Text { get; set; }

    // [Parameter]
    // public string? Value { get; set; }
    string? _value;

    [Parameter]
    public bool ReadOnly { get; set; }

    // [Parameter]
    // public EventCallback<string?> ValueChanged { get; set; }

    // [Parameter]
    // public bool Required { get; set; }

    // [Parameter]
    // public string? ErrorMessage { get; set; }

    // [Parameter]
    // public bool IsDisabled { get; set; } = false;

    // [Inject] protected IJSRuntime JSRuntime { get; set; }

    // protected string? Disabled => IsDisabled ? "disabled" : null;


    protected async Task JObjectAsync(string objName, Func<IJSObjectReference, ValueTask> operateAsync)
    {
        var obj = await JSRuntime.InvokeAsync<IJSObjectReference>("getObject", objName);
        if (obj == null)
        {
            return;
        }
        await operateAsync(obj);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JObjectAsync("PageUtil", utl => utl.InvokeVoidAsync("setAutoComplete", $"#{Id}-input"));
        }
    }

    protected override async Task OnParametersSetAsync()
    {
        if (string.IsNullOrWhiteSpace(Value))
        {
            InputFilter = Text = null;
            return;
        }

        _value = Value;
        Items = new List<SelectedItem>()
            {
                new SelectedItem("a","zg中国"),
                new SelectedItem("b","mg美国")
            };
        if (Items!.Any(x => x.Value == Value))
        {
            SelectedItem = Items!
           .FirstOrDefault(p => p.Value.Equals(Value));
        }
        InputFilter = Text = SelectedItem!.Text;
    }

    protected override void OnInitialized()
    {
        // if (Required)
        // {
        //     Attributes["required"] = true;
        // }

        if (string.IsNullOrWhiteSpace(Value))
        {
            return;
        }

        InputFilter = Text;
    }

    async Task OnKeydownAsync(KeyboardEventArgs e)
    {
        if (string.IsNullOrWhiteSpace(InputFilter))
        {
            return;
        }

        if (e.Code == "Enter" || e.Code == "NumpadEnter")
        {
            if (Items?.Count > 0)
            {
                await SelectItemAsync(Items[0]);
            }
        }
    }

    async Task OnInputAsync(ChangeEventArgs e)
    {
        InputFilter = e.Value?.ToString();

        if (InputFilter?.Length >= 1)
        {
            Items = new List<SelectedItem>()
            {
                new SelectedItem("a","zg中国"),
                new SelectedItem("b","mg美国")
            };

            Items = Items.Where(x => x.Text.StartsWith(InputFilter)).ToList();
        }
        else if (string.IsNullOrWhiteSpace(InputFilter))
        {
            Value = null;
            SelectedItem = null;
            await ValueChanged.InvokeAsync(null);
            Items = null;
        }
    }

    Task OnBlurAsync(FocusEventArgs e)
    {
        InputFilter = (SelectedItem == null ? string.IsNullOrWhiteSpace(Value) ? null : Text : SelectedItem.Text);
        return Task.CompletedTask;
    }

    async Task SelectItemAsync(SelectedItem item)
    {
        SelectedItem = item;
        InputFilter = Text = item.Text;

        Value = item.Value;
        await ValueChanged.InvokeAsync(item.Value);

        Items = null;
        await RefThis.FocusAsync();
    }

}
